<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />

      <!-- 进度条组件 -->
      <el-progress v-if="showprogtess" type="circle" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')
// 实例化对象
const cos = new COS({
  SecretId: 'AKIDGJAwUmpiQvDHArKYZMm151lEUYSEqFQM', // 身份识别ID
  SecretKey: 'rVxsbFj1A6rdaWRKB1pldv583sb9Umvw' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    // imgUrl: {
    //   type: String,
    //   default: ''
    // },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',

      percentage: 0,

      showprogtess: false
    }
  },

  // 只要传入的发生变化，就触发侦听，要想使的data中的数据始终和传入的props保持一致，必须使用watch监听
  watch: {
    value() {
      this.imageUrl = this.value
    }
  },

  methods: {
    // 完成头像的上传
    upload(res) {
      if (res.file) {
        this.showprogtess = true
        // 执行上传操作
        cos.putObject({
          Bucket: 'yuanxun-1313015793', /* 存储桶 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
            // this.showProgress = false
          }
        }, (err, data) => {
          // 上传成功或者失败都会执行这个回调
          console.log(err, data)
          // 上传成功之后
          if (data.statusCode === 200) {
            this.imageUrl = `https://${data.Location}`
            this.$emit('get-url', this.imageUrl) // 发送子组件imgurl 父组件通过自定义事件接收
            this.showprogtess = false
          }
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>
